package com.example.servlet;

import com.example.dao.UserDao;
import com.example.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    private User user = null;
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        user = userDao.getUserByUsernameAndPassword(username, password);
        if(user != null){
            request.setAttribute("msg","登录成功！！");
            request.getSession().setAttribute("user",user);
//            if(user.isIsAdmin()){
//                response.sendRedirect(request.getContextPath()+"/admin/index.jsp");
//            }else{
//                response.sendRedirect(request.getContextPath()+"/NovelMainServlet");
//            }
            response.sendRedirect(request.getContextPath()+"/NovelMainServlet");
        }else{
            boolean flag = userDao.checkUsername(username);
            if(flag){
                request.setAttribute("msg","密码错误！");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }else{
                request.setAttribute("msg","用户名不存在！");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
